#!/usr/bin/python

#This kitchen was created by bikcmp. DO NOT REMOVE THIS HEADER.
#This is FREE software.  You are free to 
#Please consider this a VERY early release.
import httplib, os, zipfile
from config import Config

f = file('Kitchen.conf')
cfg = Config(f)


def cleanUP(): #Saves the config file and cleans up any lose ends that may be there
	f = file('Kitchen.conf' , 'w')
	cfg.save(f)
	zipfile.ZipFile.close(zip)
	exit()

def setSDK():
        #global androidsdk1
        #global androidsdk2
        found = False
        while not found:
                cfg.androidsdk1=raw_input("Please enter the location of the Android SDK: ")
                cfg.androidsdk1 = cfg.androidsdk1.rstrip('/')
                cfg.androidtools = "/tools/"
                cfg.androidsdk2=cfg.androidsdk1 + cfg.androidtools
                found = os.path.isfile(cfg.androidsdk2 + "adb")
                if found == False:
                        print "I'm sorry, I didn't find adb in the location you gave"
                        print "Please try again"
        

def zip_Add():
	found = False
	while not found:
	        print 'Please enter the file you would like to add to the rom:'
		toAdd = raw_input("")
		found = os.path.isfile(toAdd)
		if not found:
			print "The file was not found, please try again"
	print 'Please enter where you would like to put the file'
	print 'NOTE: ADD THE NAME OF THE FILE AS WELL'
	print 'For Example: /system/app/launcher.apk'
	location = raw_input('')
	zipfile.ZipFile.write(zip,toAdd,location)
	print "File Added!"
	print 'Note: You must close the program properly or select write changes'
	print 'Before you will see the file added to the zip'
	print ''

def zip_List():
	print zipfile.ZipFile.namelist(zip)

def zip_Set():
	global zip
	if cfg.zipedRom == '':
	        found = False
       		while not found:
                	print "Before we begin, please enter the location of the ziped rom"
                	print "You would like to modify:"
                	cfg.zipedRom = raw_input()

                	#Test to see if the file given is a valid zip file
                	returned = zipfile.is_zipfile(cfg.zipedRom)
                	if returned == False:
                        	print "I'm sorry, the file you gave is not a vaild zip file"
                        	found = False
                	elif returned == True:
                        	found = True
                        	print "Zip found!"
	zip = zipfile.ZipFile(cfg.zipedRom, 'a')
        
def mod_Zip():
        #Funtion to modify zip
        #Removed from main section to clean up code
	zip_Set()

	zip = zipfile.ZipFile(cfg.zipedRom)

	finished = False
	while not finished:
       		print ""
        	print "What would you like to do with the rom?"
        	print ""
		print "1) List the files in a zip"
		print "2) Add a file to the zip TODO"
		print "3) Nothing yet"
		print "9) Return to main menu"
		print "0) Exit Program"        
        	selection2 = raw_input('Please enter your selection: ')

        	if selection2 == "0":
			cleanUP()
		elif selection2 == "1":
			zip_List()
		elif selection2 == "2":
			zip_Add()
		elif selection2 == "3":
			print "TODO"
		elif selection2 == "9":
			finished = True
                                       
print "Pancake kitchen 0.96 for Linux"
#print "Checking if you have the latest version."
#kitchenversion = "0.95"
#Check for updates
#conn = httplib.HTTPConnection("iaf83h0-in-f48.apps.bikcmp.com")
#conn.request("GET", "/dl/version.linux.txt")
#r1 = conn.getresponse()
#print r1.status, r1.reason
#data1 = r1.read()
#End of version check

#Is there a newer version released?
#if data1 == "0.95" :
#       print "Your version of the Pancake Kitchen is up to date."
#       print ""
#
#elif data1 > kitchenversion:
#       #If there is a new version...
#       #Get the download link:
#       conn = httplib.HTTPConnection("iaf83h0-in-f48.apps.bikcmp.com")
#       conn.request("GET", "/dl/update.linux.txt")
#       r2 = conn.getresponse()
#       print r2.status, r2.reason
#       downloadlink = r2.read()
#       #Tell the user:
#       print "You can download it at:"
#       print downloadlink
#       print ""
#       raw_input('Press enter to continue.')
#       print ""

   
# Disabled due to bugs
#
#       downloadupdate=raw_input('Do you want the program to download it for you?  (Y/N)')
#       if downloadupdate == "Y":
#               downloadlocation=raw_input('Where should I download the new version? ')
#               print "Downloading to: ", downloadlocation
#               subprocess.Popen(["wget", downloadlink], cwd=downloadlocation)
#               wait=raw_input("")

#       elif downloadupdate == "y":
#               downloadlocation=raw_input('Where should I download the new version? ')
#               if downloadlocation == "":
#                       print "Please enter a valid location."
#               
#               print "Downloading to: ", downloadlocation
#               subprocess.Popen(["wget", downloadlink], cwd=downloadlocation)
#               wait=raw_input("")


#elif kitchenversion > data1:
#       print "Your version of the Pancake Kitchen is up to date!"
#       print ""

print ""
print "You will now be asked for the location of the Android SDK."
print "Please enter the location of the SDK"
print "Example: /androidsdk/ or /androidsdk"
print "Note: Don't put in any directories, such as /androidsdk/tools/, use the root directory of the SDK."
print ""
#Set variables

#Checks to make sure that there is a value for the sdk, if not, adds one
if cfg.androidsdk1 == '':
        setSDK()
        print ""
        print "The Android SDK location is now set to: ", cfg.androidsdk1

while True:
        print ""
        print "Please make a selection below."
        print ""
        print "1) Change location of the Android SDK"
        print "2) Add application to phone"
        print "3) Push a file to the phone"
        print "4) Debug information"
        print "5) Sign a Zip file"
	print "6) Modify a Rom"
        print "0) Exit"

        selection1=raw_input('Please enter your selection: ')

        if selection1 == "1":
                print "You will now be asked for the location of the Android SDK."
                setSDK()
                print "The location of the Android SDK has been changed to: ", cfg.androidsdk1

        elif selection1 == "2":
                Failed = True #Assumes not succseful, just here for first run
                while Failed:
                        print "Please enter the full path of the application you would like to install."
                        print "Example:  /android/programs/program.apk"
                        app_name=raw_input("Please enter the location of the application you would like to install to your phone.  ")
                        os.chdir(cfg.androidsdk2)
                        returned = os.system("./adb install " + app_name)
                        print "Installing ..."
                        if returned == 256:
                                print  ""
                                print "I'm sorry, the app you specified could not be found, or the phone could not be found"
                                print "Please check the file path and make sure that the phone is connected and try again"
                                Failed = True
                        elif returned == 32512:
                                print "Adb chould not be found. Please update the SDk location and try again"
                                Failed = False #Breaks the loops so user can change the sdk
                        elif returned == 0:
                                print "Application Installed"
                                Failed = False
                        else:
                                print "An Unknown Error as occured"
                        
                        if Failed:
                                answer = raw_input("Would you like to try again? (Y/n)")
                                if answer == "N" or answer == "n":
                                        Failed = False
                #subprocess.Popen(["./adb", "install", app_name], cwd=cfg.androidsdk2)
                #wait1=raw_input('')
        
        elif selection1 == "3":
                Failed = True #Assume it didn't work for loop
                while Failed:
                        print ""
                        pushArrow = raw_input("Please enter the location of the file you would like pushed to your phone: ")
                        pushTarget = raw_input("Where would you like the file to be pushed to? (Full path please): ")
                        os.chdir(cfg.androidsdk2)
                        returned = os.system("./adb push " + pushArrow + " " + pushTarget)
                        print "Pushing ...."
                        if returned == 256:
                                print ""
                                print "The file you want pushed was not found"
                                Failed = True
                        elif returned == 0:
                                print ""
                                print "File pushed!"
                                print ""
                                Failed = False
                        else:
                                print ""
                                print "An unknown error as occured"
                                Failed = True
                                print ""

                        if Failed:
                                print ""
                                answer = raw_input("Would you like to try again? (Y/n)")
                                if answer == "N" or answer == "n":
                                        Failed = False

        elif selection1 == "4":
                print "Debug information.  Include this in bug reports!"
                print ""
                print "Pancake kitchen 0.95 for Linux"          
                print "androidsdk1 = ", cfg.androidsdk1
                print "androidsdk2 = ", cfg.androidsdk2
                print "selection1 = ", selection1
                break
                #subprocess.Popen(["adb", "push", app_name, "/system/"], cwd=androidsdk1)
                #subprocess.Popen(["adb", "push", app_name, "/system/"], cwd=androidsdk1)
                #break

        elif selection1 == "5":
                print "Please enter the full path of the zip you would like to sign"
                print ""
                zip_name = raw_input("Please enter the location of the Zip file you would like signed:  ")

        elif selection1 == "6":
                mod_Zip()
                
        elif selection1 == "0":
                cleanUP()

###### END OF FILE ####
